package com.yinhai.asynctask;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.yinhai.model.IMUserGroup;
import com.yinhai.service.IMUserGroupServiceImpl;

import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;

public class GetInitUserGroupListTask  extends AsyncTaskForHttp{
	String retStr = null;
	private Context context;
	private IMUserGroupServiceImpl imUserGroupService;
	private String groupId;
	public GetInitUserGroupListTask(Context context,String groupId) {
		super(context,false);
		this.context = context;
		imUserGroupService = new IMUserGroupServiceImpl(context);
		this.groupId = groupId;
	}
	
	public GetInitUserGroupListTask(Context context, boolean autoForword) {
		super(context, autoForword);
	}

	public GetInitUserGroupListTask(Context context, int timeoutRequestCount,
			boolean autoForword) {
		super(context, timeoutRequestCount, autoForword);
	}
	@Override
	protected void parse(Map<String, Object> result) {
		this.retStr = (String)result.get(AsyncTaskContext.RESPONSE_CONTENT);
		JSONObject jo;
		try {
			jo = new JSONObject(retStr);
			JSONObject jo1 = null;
			if("0".equals(jo.getString("status"))) {
				JSONArray ja = jo.getJSONArray("dataList");
				imUserGroupService.deleteUserGroup();
				IMUserGroup userGroup = null;
				List<IMUserGroup> users = new ArrayList<IMUserGroup>();
				for(int i = 0; i < ja.length(); i++) {
					userGroup = new IMUserGroup();
					jo1 = ja.getJSONObject(i);
					userGroup.setGroupId(jo1.getString("groupId"));
					userGroup.setUserId(jo1.getString("phone"));
					userGroup.setUserName(jo1.getString("name"));
					users.add(userGroup);
//					imUserGroupService.insert(userGroup);
				}
				SQLiteDatabase db = this.context.openOrCreateDatabase("im.db", Context.MODE_PRIVATE, null);  
		        db.beginTransaction();  
		        for(int j = 0; j < users.size(); j++) {
		        	 db.execSQL("INSERT INTO im_user_group_test(group_id,user_id,user_name)" +
			        	 		" values(?, ?, ?)" ,  
			                     new Object[]{users.get(j).getGroupId(),users.get(j).getUserId(),users.get(j).getUserName()});
				}
		        db.setTransactionSuccessful();  
		        db.endTransaction();  
				//刷新群组用户列表
		        db.close();
				Intent imgroupBroadcast = new Intent("com.im.imusergroupref");
				imgroupBroadcast.putExtra("groupId", groupId);
				context.sendBroadcast(imgroupBroadcast);
			} 
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
}
